package top.kpromise.user.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.*;
import top.kpromise.user.data.Config;
import top.kpromise.user.model.repuest.KongUserInfo;
import top.kpromise.user.model.response.UserInfoModel;
import top.kpromise.user.model.response.UserModel;
import top.kpromise.user.response.Result;
import top.kpromise.user.service.*;
import top.kpromise.user.utils.DateUtils;
import top.kpromise.user.utils.RegularUtils;
import top.kpromise.user.utils.StringUtils;

import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserInfoController {

    private final UserService userService;
    private final UserInfoService userInfoService;

    public UserInfoController(UserService userService, UserInfoService userInfoService) {
        this.userService = userService;
        this.userInfoService = userInfoService;
    }

    private Map<String, Object> checkLogin(String userId) {
        if (userId == null) {
            return Result.error("用户未登录");
        }
        UserModel userModel = userService.findUserById(userId);
        if (userModel == null) {
            return Result.error("用户不存在");
        }
        if (userModel.getEnabled() != 1) {
            return Result.error("用户已禁用");
        }
        return Result.data(userModel, "");
    }

    @RequestMapping(path = "/userInfo", method = RequestMethod.GET)
    public Map<String, Object> getUserInfo(@RequestHeader("userId") String userId,
                                           @RequestHeader("originId") String originId) {
        Map<String, Object> checkLoginResult = checkLogin(userId);
        UserModel userModel = (UserModel) checkLoginResult.get("data");
        if (userModel == null) {
            return checkLoginResult;
        }
        UserInfoModel userInfoModel = userInfoService.getByUserId(userModel.getId());
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            userInfoModel.setPermission(objectMapper.readValue(originId, KongUserInfo.class).getPermission());
        }catch (Exception e) {
            e.printStackTrace();
        }
        return Result.data(userInfoModel, "数据获取成功");
    }

    @RequestMapping(path = "/userInfo/{field}", method = RequestMethod.POST)
    public Map<String, Object> updateUserInfo(@RequestHeader("userId") String userId,
                                              @PathVariable("field") String field, String newValue) {
        Map<String, Object> checkLoginResult = checkLogin(userId);
        UserModel userModel = (UserModel) checkLoginResult.get("data");
        if (userModel == null) {
            return checkLoginResult;
        }
        switch (field) {
            case "nickName":
                return updateNickName(userModel, newValue);
            case "birthday":
                return updateBirthday(userModel, newValue);
            case "profilePhoto":
                return updateProfilePhoto(userModel, newValue);
            case "link":
                return updateLink(userModel, newValue);
            case "city":
                return updateCity(userModel, newValue);
            case "province":
                return updateProvince(userModel, newValue);
            case "signature":
                return updateSignature(userModel, newValue);
            case "gender":
                return updateGender(userModel, newValue);
            default:
                return Result.error("该属性不支持修改");
        }
    }

    private Map<String, Object> updateNickName(UserInfoModel userInfoModel, String newValue) {
        if (newValue == null) {
            return Result.error("请输入昵称");
        }
        if (newValue.length() < Config.minNickNameLen) {
            return Result.error("昵称不能少于" + Config.minNickNameLen + "位");
        }
        if (newValue.length() > Config.maxNickNameLen) {
            return Result.error("昵称不能大于" + Config.maxNickNameLen + "位");
        }
        userInfoModel.setNickName(newValue);
        return null;
    }

    private Map<String, Object> updateNickName(UserModel userModel, String newValue) {
        UserInfoModel userInfoModel = userInfoService.getByUserId(userModel.getId());
        Map<String, Object> result = updateNickName(userInfoModel, newValue);
        if (result != null) {
            return result;
        }
        userInfoService.update(userInfoModel);
        return Result.data(userInfoModel, "昵称更新成功");
    }

    private Map<String, Object> updateBirthday(UserInfoModel userInfoModel, String newValue) {
        if (newValue == null) {
            return Result.error("请输入生日");
        }
        Date birthday = DateUtils.parseBirthday(newValue);
        if (birthday == null) {
            return Result.error("生日输入不合法");
        }
        Date now = DateUtils.currentDate();
        if (birthday.after(now)) {
            return Result.error("亲，" + DateUtils.formatBirthday(birthday) + " 您肯定还没出生呢");
        }
        userInfoModel.setBirthday(birthday);
        return null;
    }

    private Map<String, Object> updateBirthday(UserModel userModel, String newValue) {
        UserInfoModel userInfoModel = userInfoService.getByUserId(userModel.getId());
        Map<String, Object> result = updateBirthday(userInfoModel, newValue);
        if (result != null) {
            return result;
        }
        userInfoService.update(userInfoModel);
        return Result.data(userInfoModel, "生日更新成功");
    }

    private Map<String, Object> updateProfilePhoto(UserInfoModel userInfoModel, String newValue) {
        if (!RegularUtils.isUrl(newValue)) {
            return Result.error("头像url不合法");
        }
        userInfoModel.setProfilePhoto(newValue);
        return null;
    }

    private Map<String, Object> updateProfilePhoto(UserModel userModel, String newValue) {
        UserInfoModel userInfoModel = userInfoService.getByUserId(userModel.getId());
        Map<String, Object> result = updateProfilePhoto(userInfoModel, newValue);
        if (result != null) {
            return result;
        }
        userInfoService.update(userInfoModel);
        return Result.data(userInfoModel, "头像更新成功");
    }

    private Map<String, Object> updateLink(UserInfoModel userInfoModel, String newValue) {
        if (!RegularUtils.isUrl(newValue)) {
            return Result.error("url不合法");
        }
        userInfoModel.setLink(newValue);
        return null;
    }

    private Map<String, Object> updateLink(UserModel userModel, String newValue) {
        UserInfoModel userInfoModel = userInfoService.getByUserId(userModel.getId());
        Map<String, Object> result = updateLink(userInfoModel, newValue);
        if (result != null) {
            return result;
        }
        userInfoService.update(userInfoModel);
        return Result.data(userInfoModel, "主页更新成功");
    }

    private Map<String, Object> updateCity(UserInfoModel userInfoModel, String newValue) {
        if (newValue == null) {
            return Result.error("请输入城市");
        }
        if (newValue.length() < Config.minCityLen) {
            return Result.error("城市长度不能少于 " + Config.minCityLen + " 位");
        }
        userInfoModel.setCity(newValue);
        return null;
    }

    private Map<String, Object> updateCity(UserModel userModel, String newValue) {
        UserInfoModel userInfoModel = userInfoService.getByUserId(userModel.getId());
        Map<String, Object> result = updateCity(userInfoModel, newValue);
        if (result != null) {
            return result;
        }
        userInfoService.update(userInfoModel);
        return Result.data(userInfoModel, "城市更新成功");
    }

    private Map<String, Object> updateProvince(UserInfoModel userInfoModel, String newValue) {
        if (newValue == null) {
            return Result.error("请输入省名");
        }
        if (newValue.length() < Config.minCityLen) {
            return Result.error("省名长度不能少于 " + Config.minCityLen + " 位");
        }
        userInfoModel.setProvince(newValue);
        return null;
    }

    private Map<String, Object> updateProvince(UserModel userModel, String newValue) {
        UserInfoModel userInfoModel = userInfoService.getByUserId(userModel.getId());
        Map<String, Object> result = updateProvince(userInfoModel, newValue);
        if (result != null) {
            return result;
        }
        userInfoService.update(userInfoModel);
        return Result.data(userInfoModel, "省份更新成功");
    }

    private Map<String, Object> updateSignature(UserInfoModel userInfoModel, String newValue) {
        if (newValue == null) {
            return Result.error("请输入签名");
        }
        if (newValue.length() < 1) {
            return Result.error("签名不能为空");
        }
        userInfoModel.setSignature(newValue);
        return null;
    }

    private Map<String, Object> updateSignature(UserModel userModel, String newValue) {
        UserInfoModel userInfoModel = userInfoService.getByUserId(userModel.getId());
        Map<String, Object> updateSignatureResult = updateSignature(userInfoModel, newValue);
        if (updateSignatureResult != null) {
            return updateSignatureResult;
        }
        userInfoService.update(userInfoModel);
        return Result.data(userInfoModel, "签名更新成功");
    }

    private Map<String, Object> updateGender(UserInfoModel userInfoModel, int gender) {
        if (gender < 1 || gender > 3) {
            return Result.error("性别输入不合法");
        }
        userInfoModel.setGender(gender);
        return null;
    }

    private Map<String, Object> updateGender(UserModel userModel, String newValue) {
        int gender = StringUtils.getInt(newValue, -1);
        UserInfoModel userInfoModel = userInfoService.getByUserId(userModel.getId());
        Map<String, Object> updateGenderResult = updateGender(userInfoModel, gender);
        if (updateGenderResult != null) {
            return updateGenderResult;
        }
        userInfoService.update(userInfoModel);
        return Result.data(userInfoModel, "性别更新成功");
    }

    @RequestMapping(path = "/userInfo", method = RequestMethod.POST)
    public Map<String, Object> updateUserInfo(@RequestHeader("userId") String userId,
                                              @RequestBody UserInfoModel userInfoModel) {
        Map<String, Object> checkLoginResult = checkLogin(userId);
        UserModel userModel = (UserModel) checkLoginResult.get("data");
        if (userModel == null) {
            return checkLoginResult;
        }

        UserInfoModel oldUserInfo = userInfoService.getByUserId(userId);
        Map<String, Object> result = null;
        if (userInfoModel.getNickName() != null) {
            result = updateNickName(oldUserInfo, userInfoModel.getNickName());
            if (result != null) {
                return result;
            }
        }

        if (userInfoModel.getBirthday() != null) {
            result = updateBirthday(oldUserInfo, DateUtils.formatBirthday(userInfoModel.getBirthday()));
            if (result != null) {
                return result;
            }
        }

        if (userInfoModel.getProfilePhoto() != null) {
            result = updateProfilePhoto(oldUserInfo, userInfoModel.getProfilePhoto());
            if (result != null) {
                return result;
            }
        }

        if (userInfoModel.getLink() != null) {
            result = updateLink(oldUserInfo, userInfoModel.getLink());
            if (result != null) {
                return result;
            }
        }

        if (userInfoModel.getCity() != null) {
            result = updateCity(oldUserInfo, userInfoModel.getCity());
            if (result != null) {
                return result;
            }
        }

        if (userInfoModel.getProvince() != null) {
            result = updateProvince(oldUserInfo, userInfoModel.getProvince());
            if (result != null) {
                return result;
            }
        }

        if (userInfoModel.getSignature() != null) {
            result = updateSignature(oldUserInfo, userInfoModel.getSignature());
            if (result != null) {
                return result;
            }
        }

        if (userInfoModel.getGender() != 0) {
            result = updateGender(oldUserInfo, userInfoModel.getGender());
            if (result != null) {
                return result;
            }
        }
        userInfoService.update(oldUserInfo);
        return Result.data(oldUserInfo, "用户信息更新成功");
    }
}
